package com.huang.day7;

import org.junit.jupiter.api.Test;

/**
 * @author HuangShen
 * @Description
 * @create 2021-04-06 9:41
 */
public class MyTest {


    public static void main(String[] args) {
        Chopstick chopstick1 = new Chopstick("1");
        Chopstick chopstick2 = new Chopstick("2");
        Chopstick chopstick3 = new Chopstick("3");
        Chopstick chopstick4 = new Chopstick("4");
        Chopstick chopstick5 = new Chopstick("5");


        new Philosopher("员工1",chopstick1,chopstick2).start();
        new Philosopher("员工2",chopstick2,chopstick3).start();
        new Philosopher("员工3",chopstick3,chopstick4).start();
        new Philosopher("员工4",chopstick3,chopstick4).start();
        new Philosopher("员工5",chopstick4,chopstick5).start();

    }

    @Test
    public void  test1(){





    }
}




class Philosopher extends  Thread{

    Chopstick left;
    Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true){
            //左手拿筷子
            synchronized (left){
                //右手拿筷子
                synchronized (right){
                   eat();
                }
            }
        }
    }


    private  void  eat(){
        try {
            System.out.println(Thread.currentThread().getName()+"--eating.......");
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class  Chopstick{
    String name;
    public Chopstick(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "筷子{"+name+"}";
    }
}